package com.lvmama.pangolin.timer.process;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.lvmama.pangolin.common.IPTools;
import com.lvmama.pangolin.common.JSONUtil;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.IP;
import com.lvmama.pangolin.service.IPService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.HttpsUtil;
import com.lvmama.pangolin.util.SpringContextUtil;


public class GetProxyIP extends CommonJob
{

	Logger logger = Logger.getLogger(GetProxyIP.class);
	@Autowired
	private IPService iPService;
	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		
		logger.info("开始获取米扑代理IP！");
		if(iPService == null)
		{
			iPService = (IPService) SpringContextUtil.getBean(IPService.class);
		}
		try 
		{                 
            String url = "http://proxy.mimvp.com/api/fetch.php?orderid=860171011114124337&num=1000&country=中国&country_group=1&http_type=1,2&anonymous=5&result_fields=1,2,3,4,5,6,7,8,9&result_format=json";
    		String dataStr=HttpsUtil.requestGet(url);
    		JSONObject dataJson=JSONObject.fromObject(dataStr);
    		
    		if(!dataJson.containsKey("result_count")){
    			JSONArray jarr = JSONArray.fromObject(dataJson.get("result"));
    			List<IP> proxyIPVOs = new ArrayList<IP>();
    			for(int i=0;i<jarr.size();i++){
    				JSONObject result=  jarr.getJSONObject(i);
    				if(result.getDouble("ping_time")<1){
    					Date curDate = new Date();
	    				IP proxyIPVO = new IP();
	    	            proxyIPVO.setIp(result.getString("ip:port").split(":")[0]);
	    	            proxyIPVO.setIp_port(result.getString("ip:port").split(":")[1]);
	    	            proxyIPVO.setAnonymity(result.getString("anonymous"));
	    	            proxyIPVO.setIp_addr(result.getString("country"));
	    	            proxyIPVO.setIp_type(result.getString("http_type"));
	    	            proxyIPVO.setResponse_speed(result.getString("ping_time"));
	    	            proxyIPVO.setInsert_time(curDate);
	    	            proxyIPVOs.add(proxyIPVO);
    				}else{
    					logger.info("此代理IP响应时间时间过长，丢弃!" );
    				}
    			}
    			storeProxyIP(proxyIPVOs);
    		}else{
    			logger.info("邮箱不存在或订单号或订单已失效!" ); //3:邮箱不存在或未登录;订单已过期：？
    		}

            logger.info("成功插入代理IP数据！");
	        } catch (Exception e) {
	        	logger.error("获取米扑代理IP数据异常",e);
	        }
		logger.info("获取米扑代理IP结束！");
		
	}
	
	private String queryIpAttribution(String ip) throws UnsupportedEncodingException
	{ 
		String  ret = null;
		String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=Json&ip=";
		String json = HttpsUtil.requestGet(url+ip);
		if(StringTools.isValid(json))
		{
			JSONObject jo = JSONUtil.getObject(json);
			ret = URLDecoder.decode(jo.getString("country"),"UTF-8");
		}
		return ret;
		
	}
	private void storeProxyIP(List<IP> ipList) 
	{
		if(ipList != null && !ipList.isEmpty())
		{
			boolean valid = false;
			for (IP ip : ipList)
			{
				try
				{
					if(ip.getAnonymity() != null && ip.getAnonymity().contains("高匿")
							&& "中国".equals(queryIpAttribution(ip.getIp())))
					{
						valid = IPTools.checkIPTelnet(ip.getIp(), ip.getIp_port(),1000);						
						if(valid)
						{
							ip.setAvailable(1);
							iPService.insertProxyIP(ip);
							logger.info("插入成功!" );
						}
					}
					
					
				}catch(Exception e)
				{
					logger.error("验证IP有效性异常或IP入表失败！IP:"+ip.getIp() 
							+ " PORT:"+ip.getIp_port(),e);
				}
				
				
			}
			
		}
	}
	
}
